package avishay.balderman.dao;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import avishay.balderman.dao.Link.LinkType;

import java.util.logging.Logger;

public abstract class LinkHelper
{
	public static void addLink(HttpServletRequest req)
	{
		final Link link = new Link();
		final String url = req.getParameter("URL");
		final String description = req.getParameter("Description");
		final String type = req.getParameter("Type");
		link.setDescription(description);
		link.setLinkType(LinkType.valueOf(type));
		link.setUrl(url);
		addLink(link);
	}
	public static void addLink(Link link)
	{
		logger.info("About to persist the Link " + link);
		EntityManagerFactory entityManagerFactory = EMF.get();
		try
		{
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			EntityTransaction transaction = entityManager.getTransaction();
			transaction.begin();
			entityManager.persist(link);
			transaction.commit();
		}
		finally
		{
			entityManagerFactory.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static Collection<Link> getLinks(final String type)
	{
		EntityManagerFactory entityManagerFactory = EMF.get();
		try
		{
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			final String queryWherePhrase = type.equals("*") ? "" : " WHERE l.linkType ='" + type + "'";
			final String finalQuery = "SELECT l FROM Link l" + queryWherePhrase;
			Query linksQuery = entityManager.createQuery(finalQuery);
			List resultList = linksQuery.getResultList();
			return (Collection<Link>)resultList;
		}
		finally
		{
			entityManagerFactory.close();
		}
	}
	private static Logger logger = Logger.getLogger("avishay.balderman.dao.LinkHelper");
}
